package com.yc.web.servlets;

import com.yc.bean.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet(value = "/goods.action")
public class GoodsSerclet extends BaseServlet {
    protected void findAllgoods(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException, ParseException {
        Goods c = super.parseObjectFromRequest(req, Goods.class);
        int page = 1;
        if (req.getParameter("page") != null) {
            page = Integer.parseInt(req.getParameter("page"));
        }
        int limit = 2;
        if (req.getParameter("limit") != null) {
            limit = Integer.parseInt(req.getParameter("limit"));
        }
        int skip = (page - 1) * limit;
        String sql = "SELECT s.sid, s.sbrand, s.sgender, s.ssize, s.scolor, sty.style, s.sprice, s.sdescription, s.sstockquantity " +
                "FROM Shoes s " +
                "JOIN ShoeStyle sty ON s.sstyle = sty.styleid " +
                "WHERE 1=1";
        String sql2 = "select count(*) as total " +
                "FROM Shoes s " +
                "JOIN ShoeStyle sty ON s.sstyle = sty.styleid " +
                "WHERE 1=1";
        String sql3 = "SELECT photourl FROM ShoePhotos  where 1=1 and ismain='true' ";

        List<Object> params = new ArrayList<>();
        Integer sid = c.getSid();

        if (c.getSid() != null) {
            sql += " and sid=? ";
            sql2 += " and sid=? ";
            sql3 += " and sid=? ";
            params.add(c.getSid());

        }

        String sbrand = req.getParameter("sbrand");
        if (sbrand != null && !sbrand.trim().isEmpty()) {
            sql += " AND s.sbrand LIKE '%" + c.getSbrand() + "%'"; // 模糊查询 sbrand
            sql2 += " AND s.sbrand LIKE '%" + c.getSbrand() + "%'"; // 模糊查询 sbrand
        }


        if (c.getStyle() != null && !c.getStyle().trim().isEmpty()) {
            sql += " AND sty.style LIKE '%" + c.getStyle() + "%'"; // 模糊查询 style
            sql2 += " AND sty.style LIKE '%" + c.getStyle() + "%'"; // 模糊查询 style
        }

        String ssize = req.getParameter("ssize");
        if (ssize != null && !ssize.trim().isEmpty()) {
            sql += " AND s.ssize = " + c.getSsize(); // 模糊查询 ssize
            sql2 += " AND s.ssize = " + c.getSsize(); // 模糊查询 ssize
        }

        List<Goods> list = db.select(Goods.class, sql + "   order by sid limit " + limit + " offset " + skip, params.toArray());
        List<Map<String, Object>> result = db.select(sql2, params.toArray());
        List<Goods> url = db.select(Goods.class, sql3 + "   order by sid limit " + limit + " offset " + skip, params.toArray());
        int total = Integer.parseInt(result.get(0).get("total").toString());
//        String photourl= (String) result.get(0).get("photourl");
        // 遍历查询结果，获取 photourl 并加入到 Goods 对象中
        for (int i = 0; i < list.size(); i++) {
            // 假设 result 是查询结果的 List<Map<String, Object>>，且每个元素是一行数据的 Map
            String photourl = url.get(i).getPhotourl();

            // 获取当前 Goods 对象
            Goods goods = list.get(i);
            // 设置 photourl 到 Goods 对象中的 photoUrl 字段
            goods.setPhotourl(photourl);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "查询用户成功");
        map.put("data", list);
        map.put("count", total);
        super.writeObiectJson(map, resp);
    }
    protected void addGood(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException, ParseException {
        Goods c = super.parseObjectFromRequest(req, Goods.class);
        String sql = "INSERT INTO Shoes (sbrand, sgender, ssize, scolor, sstyle, sprice, sdescription, sstockquantity) VALUES (?,?,?,?,?,?,?,?)";
        String sql1 = "SELECT MAX(sid) AS sid FROM Shoes";
        String sql2 = "INSERT INTO ShoePhotos (sid, photourl, ismain) VALUES (?,?, 'true')";

        try {
            // Insert data into 'shoes' table
            int result = db.doUpdate(sql, c.getSbrand(), c.getSgender(), c.getSsize(), c.getScolor(), c.getSstyle(), c.getSprice(), c.getSdescription(), c.getSstockquantity());

            if (result > 0) {
                // Fetch last inserted ID
                List<Map<String, Object>> aid = db.select(sql1);
                if (!aid.isEmpty()) {
                    int msid;
                    String data= aid.toString();

// 使用正则表达式提取数字部分
                    Pattern pattern = Pattern.compile("\\d+"); // 匹配数字
                    Matcher matcher = pattern.matcher(data);

                    if (matcher.find()) {
                        String numberStr = matcher.group(); // 提取到的数字字符串
                        msid = Integer.parseInt(numberStr); // 将字符串转换为整数
                        int sid=msid+1;
                        c.setSid(sid);



                    // Insert photo data into 'shoePhotos' table
                        int result2 = db.doUpdate(sql2, c.getSid(), c.getPhotourl());

                        // Prepare response map
                        Map<String, Object> map = new HashMap<>();
                        if (result2 > 0) {
                            map.put("code", 0);
                            map.put("msg", "添加图片成功");
                        } else {
                            map.put("code", 1);
                            map.put("msg", "添加商品失败（插入图片失败）");
                        }
                        super.writeObiectJson(map, resp);
                        return; // Exit method after writing response
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); // Handle or log the exception as appropriate
        }

// If any step fails, return failure response
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("msg", "添加商品失败");
        super.writeObiectJson(map, resp);

    }

    public void delgoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Goods c=super.parseObjectFromRequest(req,Goods.class);
        String sql="delete from Shoes where sid=?";
        int r=db.doUpdate(sql,c.getSid());
        String sql2="delete from ShoePhotos where sid=?";
        int f=db.doUpdate(sql,c.getSid());

        Map<String,Object>map=new HashMap<String,Object>();
        if (r>0 && f>0){
            map.put("code",0);
            map.put("msg","删除用户成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"删除用户失败");
            map.put("code",1);
            map.put("msg","删除用户失败");

        }
        super.writeObiectJson(map,resp);

    }
    public void updategood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException, ParseException {
        Goods c=super.parseObjectFromRequest(req,Goods.class);
      String sql="UPDATE Shoes \n" +
              "SET sbrand = ?, \n" +
              "    sgender = ?, \n" +
              "    ssize = ?, \n" +
              "    scolor = ?, \n" +
              "    sstyle = ?, \n" +
              "    sprice = ?, \n" +
              "    sdescription = ?, \n" +
              "    sstockquantity = ?\n" +
              "WHERE sid = ?";
      int r=db.doUpdate(sql,c.getSbrand(),c.getSgender(),c.getSsize(),c.getScolor(),c.getSstyle(),c.getSprice(),c.getSdescription(),c.getSstockquantity(),c.getSid());

        Map<String,Object>map=new HashMap<String,Object>();
        if (r>0){
            map.put("code",0);
            map.put("msg","更新商品成功");
            resp.setStatus(200);
        }else {
            resp.setStatus(500,"更新商品失败");
            map.put("code",1);
            map.put("msg","更新用户失败");

        }
        super.writeObiectJson(map,resp);

    }


}
